export function checkValidIp(ip) {
  var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
  if (re.test(ip)) {
    if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256) {
      return true
    }
  }

  return false
}

export function isValidIp(ip) {
  return ip == '' ? true : checkValidIp(ip)
}

export function checkValidMultiIp(ip) {
  var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
  if (re.test(ip)) {
    if (RegExp.$1 >= 225 && RegExp.$1 <= 238) {
      return true
    }
  }

  return false
}

function getIpArray(ip) {
  var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
  let arr = re.exec(ip)
  return [arr[1], arr[2], arr[3], arr[4]]
}

export function getIpaddrList(startIp, endIp) {
  let start = getIpArray(startIp)
  let end = getIpArray(endIp)
  var ipList = []

  if ((start[0] !== end[0])
    || (start[1] !== end[1])
    || (start[2] !== end[2])) {
    return ipList
  }

  for (var i = parseInt(start[3]); i <= parseInt(end[3]); i++) {
    ipList.push(`${start[0]}.${start[1]}.${start[2]}.${i}`)
  }

  return ipList
}

export function isValidPort(port) {
  return ((port > 0) && (port < 0xFFFF))
}

export function printObj(obj) {
  for (let key in obj) {
    console.log(`[${key}]=${obj[key]}`);
  }
}

export function copyObj(dst, src) {
  for (let key in dst) {
    dst[key] = src[key]
  }
}

export function readableTime(input) {
  //TODO i18n
  var units = [{
    desc: '天',
    num: 60*60*24,
    val: 0
  }, {
    desc: '小时',
    num: 60*60,
    val: 0
  }, {
    desc: '分钟',
    num: 60,
    val: 0
  }, {
    desc: '秒',
    num: 1,
    val: 0
  }]
  var left = input
  var text = ''

  for (var i = 0; i < units.length; i++) {
    units[i].val = Math.floor(left / units[i].num)
    if (units[i].val > 0) {
      left -= (units[i].val * units[i].num)
      text += (units[i].val + units[i].desc)
    }
  }

  if (text === '') {
    text = '0'
  }

  return text 
}

export function readableSize(input) {
  var unitDesc = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
  var unitNum = 1024
  var size = input
  var left = Math.floor(size / unitNum)
  var index = 0
  var base = 1.0

  while (left > 0) {
    index++
    left = Math.floor(left / unitNum)
    base *= unitNum
    if (index + 1 >= unitDesc.length) {
      break
    }
  }

  if (0 == index) {
    return size + " " + unitDesc[0]
  } else {
    return Math.round(size / base) + " " + unitDesc[index]
  }
}

export function getQueryStringArgs() {
  var args = {}
  var qs = location.search.length > 0 ? location.search.substring(1) : ""
  var items = qs.length ? qs.split("&") : []
  for (let i = 0; i < items.length; i++) {
    var item = items[i].split("=")
    var name = decodeURIComponent(item[0])
    var value = decodeURIComponent(item[1])
    if (name.length) {
      args[name] = value
    }
  }
  return args
}

export function getTimeStr(date) {
  var now = date
  var YY = now.getFullYear()
  var MM = now.getMonth() + 1
  if (MM < 10) MM = '0' + MM
  var DD = now.getDate()
  if (DD < 10) DD = '0' + DD
  var HH = now.getHours()
  if (HH < 10) HH = '0' + HH
  var mm = now.getMinutes()
  if (mm < 10) mm = '0' + mm
  var ss = now.getSeconds()
  if (ss < 10) ss = '0' + ss

  return YY + '-' + MM + '-' + DD + 'T' + HH + ':' + mm + ':' + ss
}

export function getOppositeColor(color) {
  color = color.replace('#', '')
  var c16, c10, max16 = 15, b = []
  for (var i = 0; i < color.length; i++) {
    c16 = parseInt(color.charAt(i), 16)
    c10 = parseInt(max16 - c16, 10)
    b.push(c10.toString(16))
  }
  return '#' + b.join('')
}

export function getBackgroundColor(color) {
  color = color.replace('#', '')
  var R = parseInt(color.slice(0, 2), 16)
  var G = parseInt(color.slice(2, 4), 16)
  var B = parseInt(color.slice(4, 6), 16)
  var deep = R*0.299+G*0.587+B*0.114
  if (deep < 128) {
    return '#F0F0F0'
  } else {
    return '#0F0F0F'
  }
}

export function isValidStart(text) {
  var re = /^[^0-9]+/
  if (text ==='' 
    || re.test(text)) {
    return true
  }

  return false  
}

export function isContainSpace(text) {
  var re = /[\s]+/
  if (re.test(text)) {
    return true
  }

  return false  
}

export function isContainSpecial(text) {
  var re = /[`~!@#$%^&*()-_=+[\]{}\\|;:'",.<>?/]/
  if (re.test(text)) {
    return true
  }

  return false  
}

export function isContainNameSpecial(text) {
  //名字允许包含下面字符：@.|()-_
  var re = /[`~!#$%^&*=+[\]{}\\;:'",<>?/]/
  if (re.test(text)) {
    return true
  }

  return false  
}

export function isValidName(text) {
  return isValidStart(text) && !isContainSpace(text) && !isContainNameSpecial(text)
}

export function byteLength(str) {
  var byteLen = 0
  var len = str.length

  if(!str) {
    return 0
  }

  for(let i = 0; i < len; i++ ) {
    byteLen += str.charCodeAt(i) > 255 ? 4 : 1
  }
  
  return byteLen
}

export function checkStrong(str) {
  return /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}$/.test(str)
}

export function hex2Ipaddr(str) {
  var a = parseInt(str.slice(0, 2), 16)
  var b = parseInt(str.slice(2, 4), 16)
  var c = parseInt(str.slice(4, 6), 16)
  var d = parseInt(str.slice(6, 8), 16)

  return `${a}.${b}.${c}.${d}`
}

export function ipaddr2Hex(ip) {
  let segs = getIpArray(ip)
  var a = []
  for (let i = 0; i < segs.length; i++) {
    segs[i] = parseInt(segs[i], 10)
    a.push(Math.floor(segs[i]/16).toString(16))
    a.push((segs[i]%16).toString(16))
  }

  return a.join('')
}

export function showPublicUrl(url) {
  var re = /(.*)\:\/\/(.*):(.*)@(.*)/
  if (re.test(url)) {
    return url.replace(re, '$1://$2:*****@$4')
  } else {
    return url
  }
}

export function calRangeCross(xStart, xEnd, yStart, yEnd) {
  let cStart = Math.max(xStart, yStart)
  let cEnd = Math.min(xEnd, yEnd)

  if (cStart >= cEnd) {
    return null
  }

  return {
    start: cStart,
    end: cEnd
  }
}

//{left top right bottom}
export function calRectCross(rect1, rect2) {
  let cHoriz = calRangeCross(rect1.left, rect1.right, rect2.left, rect2.right)
  let cVerti = calRangeCross(rect1.top, rect1.bottom, rect2.top, rect2.bottom)
  if (!cHoriz || !cVerti) {
    return null
  }
  return {
    left: cHoriz.start,
    top: cVerti.start,
    right: cHoriz.end,
    bottom: cVerti.end
  }
}

export function calRelativeRect(outterRect, innerRect) {
  return {
    left: innerRect.left - outterRect.left,
    top: innerRect.top - outterRect.top,
    right: innerRect.right - outterRect.left,
    bottom: innerRect.bottom - outterRect.top,
  }
}
